package com.github.itdachen.auth.oauth.manager.impl;

import com.github.itdachen.auth.interfaces.constants.AppConstants;
import com.github.itdachen.auth.oauth.manager.IAuthorizedResourcesManager;
import com.github.itdachen.auth.oauth.mapper.IAuthorizedResourcesMapper;
import com.github.itdachen.framework.context.constants.UserTypeConstant;
import com.github.itdachen.framework.context.constants.YesOrNotConstant;
import com.github.itdachen.framework.context.userdetails.UserInfoDetails;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * AuthorizedResourcesManagerImpl
 *
 * @author 王大宸
 * @date 2025-02-05 15:14
 */
@Component
public class AuthorizedResourcesManagerImpl implements IAuthorizedResourcesManager {

    private final IAuthorizedResourcesMapper authorizedResourcesMapper;

    public AuthorizedResourcesManagerImpl(IAuthorizedResourcesMapper authorizedResourcesMapper) {
        this.authorizedResourcesMapper = authorizedResourcesMapper;
    }


    /***
     * 获取可访问的资源ID
     *
     * @author 王大宸
     * @date 2025/2/5 15:18
     * @param userDetails userDetails
     * @return java.util.List<java.lang.String>
     */
    @Override
    public List<String> obtainAccessibleElementId(UserInfoDetails userDetails)  {
        try {
            final String appId = AppConstants.APP_ID;
            /* 超级管理员, 查询所有 */
            if (UserTypeConstant.SUPER_ADMINISTRATOR.equals(userDetails.getUserType())
                    && YesOrNotConstant.Y.equals(userDetails.getRoleFlag())) {
                return authorizedResourcesMapper.obtainAllElement(appId);
            }
            // 查询不需要授权的菜单
            List<String> authMenuList = authorizedResourcesMapper.findNoopAuthElement(appId);
            // 查询岗位菜单
            List<String> clazzAuthMenuAndElement = authorizedResourcesMapper.findClazzAuthElement(appId, userDetails.getTenantId(), userDetails.getRoleId());
            /* 授权的与不需要授权的合并 */
            authMenuList.addAll(clazzAuthMenuAndElement);
            if (authMenuList.isEmpty()) {
                return new ArrayList<>();
            }
            /* 去重 */
            final Set<String> hashSet = new HashSet<>(authMenuList);
            return new ArrayList<>(hashSet);
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }


}
